import cv2
import numpy as np

video_path = './vtest.avi'
cap = cv2.VideoCapture(video_path)
# 混合高斯模型
fgbg = cv2.createBackgroundSubtractorMOG2()
thresh = 200
color = np.random.randint(0, 255, (100, 3))

while True:
    ret, frame = cap.read()
    if not ret:
        break

    fgmask = fgbg.apply(frame)
    _, fgmask = cv2.threshold(fgmask, 30, 0xff, cv2.THRESH_BINARY)

    bgImage = fgbg.getBackgroundImage()

    cnts = cv2.findContours(fgmask.copy(), cv2.RETR_EXTERNAL,
                            cv2.CHAIN_APPROX_SIMPLE)
    count = 0
    color1 = 0x00
    color2 = 0x0f
    color3 = 0x00
    for c in cnts[1]:
        area = cv2.contourArea(c)
        if (area < thresh):
            continue
        count += 1
        x, y, w, h = cv2.boundingRect(c)
        print("X:{} Y:{} , size :{} ".format(x, y, w * h))
        color1 = color1 + 0x1f
        color2 = color2 - 0x2f
        color3 = color3 + 0x38
        cv2.rectangle(frame, (x, y), (x + w, y + h), (color1, color2, color3),
                      2)
        cv2.putText(frame, str(count), (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.4,
                    (0, 225, 0), 1) #加编号

    print('count', count, 'targets', '\n')
    cv2.imshow('frame', frame)
    cv2.imshow('Background', bgImage)
    cv2.imshow('fgmask', fgmask)

    key = cv2.waitKey(30)
    if key == 27:
        break
cap.release()
cv2.destroyAllWindows()
